package com.atom.module.coroutine.dispatcher

import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger

// 默认分发器
object DefaultDispatcher : Dispatcher {
    // 线程组
    private val threadGroup = ThreadGroup("DefaultDispatcher")

    // 线程索引
    private val threadIndex = AtomicInteger(0)

    // 线程池
    private val executor =
        Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1) { runnable ->
            Thread(
                threadGroup,
                runnable,
                "${threadGroup.name}-worker-${threadIndex.getAndIncrement()}"
            ).apply { isDaemon = true }
        }

    // 分发执行 ,实际上进入线程池进行执行
    override fun dispatch(block: () -> Unit) {
        executor.submit(block)
    }

}